package org.anti996.lms.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.anti996.lms.model.Customer;
import org.anti996.lms.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 客户表 前端控制器
 * </p>
 *
 * @author The Anti996 Authors
 * @since 2022-07-15
 */
@Slf4j
@RestController
@RequestMapping("/lms/customer")
@CrossOrigin(origins = "*")
public class CustomerController {
    @Autowired
    private CustomerService customerService;
    /**
     * 获取客户列表
     *
     * @return 客户列表
     */
    @GetMapping
    public List<Customer> customersList() { return customerService.list(); }

    /**
     * 获取客户分页列表
     *
     * @param no 第no个页面
     * @param sz 每个页面的数据条数
     * @return 分页客户列表
     */
    @GetMapping("/page/{sz}/{no}")
    public List<Customer> customersListPage(@PathVariable(name = "no") int no,
                                        @PathVariable(name = "sz") int sz) {
        Page<Customer> page = customerService.page(new Page<>(no, sz));
        return page.getRecords();
    }

    /**
     * 根据客户编号获取客户信息
     *
     * @param c_id 客户编号
     * @return 查询到的客户信息
     */
    @GetMapping("/{id}")
    public Customer customer(@PathVariable(name = "id") int c_id) {
        return customerService.getById(c_id);
    }

    /**
     * 新增客户
     *
     * @param customer 新增客户信息
     * @return 创建结果
     */
    @PostMapping(consumes = "application/json")
    public boolean insertCustomer(@RequestBody Customer customer) {
        return customerService.save(customer);
    }

    /**
     * 更新客户信息
     *
     * @param c_id      客户编号
     * @param customer 新的客户信息
     * @return 更新是否成功
     */
    @PutMapping(path = "/{id}", consumes = "application/json")
    public boolean updateCustomer(@PathVariable(name = "id") int c_id,
                                @RequestBody Customer customer) {
        return customerService.updateById(customer);
    }

    /**
     * 删除指定客户的数据
     *
     * @param c_id 客户编号
     * @return 是否删除成功
     */
    @DeleteMapping("/{id}")
    public boolean removeCustomer(@PathVariable(name = "id") int c_id) {
        return customerService.removeById(c_id);
    }

    @GetMapping("/getIdbyname/{name}/{phone}/{addr}")
    public int getIdbyname(@PathVariable(name = "name") String username,
                               @PathVariable(name = "phone") String phone,
                               @PathVariable(name = "addr") String addr) {
        Customer customer=customerService.getIdbynps(username,phone,addr);
        if (customer!=null)
            return customer.getCId();
        else return 0;}

    @GetMapping("/find")
    public List<Customer> findCustomerByName(@RequestParam(name = "name") String name) {
        return customerService.findCustomersByName(name);
    }
}
